from fastapi import FastAPI, Depends, HTTPException, Request, BackgroundTasks
import os
import sys
import subprocess
import logging

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from .database.database import get_db, engine, Base
from sqlalchemy.orm import Session

app = FastAPI()

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger("backend")

@app.post("/api/init-db-config")
async def init_db_config():
    """初始化数据库配置API"""
    try:
        # 执行初始化脚本
        script_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "init_db_config.py")
        
        # 使用子进程执行初始化脚本
        result = subprocess.run(
            [sys.executable, script_path],
            capture_output=True,
            text=True,
            check=True
        )
        
        return {
            "success": True,
            "message": "数据库配置初始化成功",
            "details": result.stdout
        }
    except subprocess.CalledProcessError as e:
        logger.error(f"初始化数据库配置失败: {e.stderr}")
        raise HTTPException(status_code=500, detail=f"初始化数据库配置失败: {e.stderr}")
    except Exception as e:
        logger.error(f"初始化数据库配置时发生错误: {str(e)}")
        raise HTTPException(status_code=500, detail=f"初始化数据库配置时发生错误: {str(e)}")

@app.get("/api/health")
async def health_check():
    """健康检查API"""
    return {"status": "ok", "message": "服务正常运行"} 